<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 资源中心->角色信息
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-row :gutter="10">
                    <el-col :xs="24" :sm="12" :lg="6">
                        <el-input v-model="query.data.roleCode" placeholder="角色编码" class="handle-input"></el-input>
                    </el-col>
                    <el-col :xs="24" :sm="12" :lg="6">
                        <el-input v-model="query.data.roleName" placeholder="角色名称" class="handle-input"></el-input>
                    </el-col>
                    <el-col :xs="24" :sm="12" :lg="6">
                        <el-select v-model="query.data.roleType" placeholder="角色类型" class="handle-select" clearable>
                            <el-option v-for="item in roleTypeList"
                                       :key="item.value"
                                       :label="item.label"
                                       :value="item.value">
                                <span style="float: left">{{ item.label }}</span>
                            </el-option>
                        </el-select>
                    </el-col>
                    <el-col :xs="24" :sm="12" :lg="6">
                        <el-select v-model="query.data.appCode" placeholder="所属应用" class="handle-select" clearable>
                            <el-option v-for="item in appList"
                                       :key="item.appCode"
                                       :label="item.appName"
                                       :value="item.appCode">
                                <span style="float: left">{{ item.appName }}</span>
                            </el-option>
                        </el-select>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :xs="24" :sm="12" style="text-align: left">
                        <el-button type="primary" icon="el-icon-search" @click="handleAdd">新增</el-button>
                    </el-col>
                    <el-col :xs="24" :sm="12" style="text-align: right">
                        <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
                        <el-button type="primary" icon="el-icon-refresh" @click="clearQueryForm">重置</el-button>
                    </el-col>
                </el-row>
            </div>

            <el-table border class="table"
                      ref="multipleTable"
                      :data="tableData"
                      header-cell-class-name="table-header"
                      @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="id" label="角色ID" width="70"></el-table-column>
                <el-table-column prop="roleCode" label="角色编码" width="180" align="center"></el-table-column>
                <el-table-column prop="roleName" label="角色名称"></el-table-column>
                <el-table-column prop="roleType" label="角色类型" align="center"></el-table-column>
                <el-table-column prop="appCode" label="所属应用" align="center"></el-table-column>
                <el-table-column prop="status" label="状态" align="center"></el-table-column>
                <el-table-column label="操作" width="130" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" icon="el-icon-edit"
                                   @click="handleEdit(scope.$index, scope.row)">
                            编辑
                        </el-button>
                        <el-button type="text" icon="el-icon-delete" class="red"
                                   @click="handleDelete(scope.$index, scope.row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination">
                <el-pagination background
                               layout="total, prev, pager, next"
                               :current-page="query.pageVo.pageNo"
                               :page-size="query.pageVo.pageSize"
                               :total="pageTotal"
                               @current-change="handlePageChange">
                </el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="角色信息管理" :visible.sync="editVisible" width="75%" :lock-scroll="false">
                <el-row :gutter="20" style="padding:15px 36px">
                    <el-col :span="14">
                        <el-form ref="form" :model="formData" label-width="70px">
                            <el-form-item label="角色编码">
                                <el-input v-model="formData.roleCode" placeholder="格式: 角色编码"></el-input>
                            </el-form-item>
                            <el-form-item label="角色名称">
                                <el-input v-model="formData.roleName" placeholder="角色名称"></el-input>
                            </el-form-item>
                            <el-form-item label="角色类型">
                                <el-radio-group v-model="formData.roleType">
                                    <el-radio-button v-for="item in roleTypeList" :label="item.value">
                                        {{ item.label }}
                                    </el-radio-button>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item label="所属应用">
                                <el-select v-model="formData.appCode" placeholder="资源所属应用编码" class="handle-select" clearable>
                                    <el-option v-for="item in appList"
                                               :key="item.appCode"
                                               :label="item.appName"
                                               :value="item.appCode">
                                        <span style="float: left">{{ item.appName }}</span>
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="角色状态">
                                <el-radio-group v-model="formData.status">
                                    <el-radio-button v-for="item in statusList" :label="item.value">
                                        {{ item.label }}
                                    </el-radio-button>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item label="备注">
                                <el-input type="textarea" v-model="formData.remark"></el-input>
                            </el-form-item>
                        </el-form>
                    </el-col>
                    <el-col :span="10">
                        <el-aside width="100%">
                            <el-row style="border: #97a8be solid 1px; min-height:360px; max-height:450px">
                                <ul id="zTreeDiv" class="ztree"></ul>
                            </el-row>
                        </el-aside>
                    </el-col>
                </el-row>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="handleSave">保 存</el-button>
                <el-button @click="editVisible = false">取 消</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import { OnionUtils } from '../../utils/onion-utils';
    import { listApp } from '../../api/appic/appInfo';
    import { fetchDictByIndex } from '../../api/resic/dictionary';
    import { doFindRole, doGetRole, doFindRoleAuthTree, doSaveRole, doDeleteRole } from '../../api/authic/role';
    import "@/components/plugins/ztree/jquery.ztree.all.js";
    import "@/components/plugins/ztree/jquery.ztree.exhide.js";
    import "@/components/plugins/ztree/metroStyle/metroStyle.css";

    export default {
        name: 'basetable',
        data() {
            return {
                query: {
                    data:{
                        roleCode: '',
                        roleType: '',
                        appCode: ''
                    },
                    pageVo:{
                        pageNo: 1,
                        pageSize: 10
                    }
                },
                pageTotal: 0,
                editVisible: false,
                editRoleAuthVisible: false,
                formData: {},
                tableData: [],
                appList: [],
                statusList: [],
                roleTypeList: [],
                menuTree: [],
                roleMenuTree: {},
                id: -1,
                idx: -1,
                defaultProps: {
                    label: 'title',
                    children: 'subs'
                },
                zTreeSetting:{
                    view: {
                        dblClickExpand: false
                    },
                    check: {
                        enable: true
                    },
                    data:{
                        simpleData:{
                            id: "id",
                            pIdKey: "pId",
                            enable: true
                        },
                        key:{
                            checked: "checked"
                        }
                    },
                    callback: {
                    }
                }
            };
        },

        //初始化页面数据
        created() {
            this.initData();
            this.findPage();
        },

        //方法区
        methods: {
            dateFormat(row,column){
                let data = row[column.property]
                if (data ===null) {
                    return ''
                }
                let dt = new Date(data)
                return dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate() + ' ' + dt.getHours() + ':' + dt.getMinutes() + ':' + dt.getSeconds()
            },

            // 初始化页面数据
            initData(){
                fetchDictByIndex("onion.tenant.type,onion.role.type,onion.role.status").then(result => {
                    this.tenantTypeList = result.data["onion.tenant.type"];
                    this.roleTypeList = result.data["onion.role.type"];
                    this.statusList = result.data["onion.role.status"];
                });
                listApp().then(result => {
                    this.appList = result.data;
                });
            },

            // 分页列表查询
            findPage(){
                doFindRole(this.query).then(result=>{
                    this.tableData = result.data.rows;
                    this.pageTotal = result.data.total || 0;
                })
            },

            // 查询按钮事件
            handleQuery(){
                this.findPage();
            },

            // 新增角色
            handleAdd(){
                this.idx = -1;
                this.formData ={"roleCode":"",
                                "roleType":"system",
                                "status":"enabled"}
                this.editVisible = true;
            },

            // 编辑角色
            handleEdit(index, row) {
                if(index <= -1){
                    this.$alert("请选择一条记录!");
                    return;
                }else{
                    this.idx = index;
                    this.formData = row;
                    this.loadRoleAndTree(row.id);
                    this.editVisible = true;
                }
            },

            // 打开角色权限配置
            handleAuthority(index, row){
                if(index <= -1){
                    this.$alert("请选择一条记录!");
                    return;
                }
                this.idx = index;
                this.formData = row;
                this.editVisible = true;
            },

            // 保存角色
            handleSave(){
                //获取选择的权限树节点
                let ztreeObj = $.fn.zTree.getZTreeObj("zTreeDiv");
                let checkedNodes = ztreeObj.getCheckedNodes(true);
                let selectMenuIds = [];
                let selectResourceIds = [];
                checkedNodes.forEach((node, index, array)=>{
                    if(node["id"].split(":").length == 2){
                        selectResourceIds.push(node["id"]);
                    }else{
                        selectMenuIds.push(node["id"]);
                    }
                });
                //装配角色数据
                this.formData.menuIds = selectMenuIds;
                this.formData.resourceIds = selectResourceIds;
                //保存角色数据
                doSaveRole(this.formData).then(result => {
                    this.$message.success(`保存成功！`);
                    if(this.idx != -1){
                        this.$set(this.tableData, this.idx, result.data);
                    }else{
                        this.findPage();
                    }
                    this.editVisible = false;
                });
            },

            // 删除角色
            handleDelete(index, row){
                // 二次确认删除
                this.$confirm('确定要删除吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    doDeleteRole(this.tableData[index].id).then(result => {
                        this.$message.success('删除成功');
                        this.tableData.splice(index, 1);
                    });
                }).catch(() => {
                    this.$alert('异常！');
                });
            },

            // 清空QueryForm
            clearQueryForm(){
                this.query.data = {};
            },

            // 多选操作
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },

            // 分页导航
            handlePageChange(val) {
                this.$set(this.query, 'pageIndex', val);
                this.findPage();
            },

            // 加载角色权限Tree
            loadRoleAndTree(roleId){
                if(OnionUtils.isEmpty(roleId)) {
                    return;
                }
                //加载菜单树
                doFindRoleAuthTree(roleId).then(result => {
                    $.fn.zTree.init($("#zTreeDiv"), this.zTreeSetting, result.data);
                });
            }
        }
    };
</script>

<style scoped>
    .handle-box {
        margin-bottom: 10px;
    }

    .handle-select {
        width: 100%;
    }

    .handle-input {
        width: 100%;
        display: inline-block;
    }

    .table {
        width: 100%;
        font-size: 14px;
    }

    .red {
        color: #ff0000;
    }

    .mr10 {
        margin-right: 10px;
    }

    .table-td-thumb {
        display: block;
        margin: auto;
        width: 40px;
        height: 40px;
    }

    ul.ztree {
        width: auto;
        min-height: 360px;
        overflow-y: auto;
    }

    div.zTreeDemoBackground{
        height: 300px;
    }

    div#zTreeMenu {
        z-index: 9999;
        position:fixed;
        visibility:hidden;
        top:0;
        background-color: #555;
        text-align: left;
        padding: 2px;
    }

    div#zTreeMenu ul li{
        margin: 1px 0;
        padding: 0 5px;
        cursor: pointer;
        list-style: none outside none;
        background-color: #DFDFDF;
    }

</style>